package com.example.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.CertificateDao;
import com.example.domain.Certificate;
import com.example.result.Result;
import com.example.result.ResultFactory;
import com.example.service.CertificateService;
import com.example.tool.DateTool;

/**
 * @author 袁小弘
 * @describe 证书服务层接口实现
 * @date 2020-01-01
 */
@Service
public class CertificateServiceImpl implements CertificateService {

    @Autowired
    CertificateDao certificateDao;

    /**
     * @describe 添加证书信息
     */
    @Override
    public Result addCertificate(Certificate certificate) {
        if (certificate != null) {
            //获取系统当前时间作为记录创建时间
            certificate.setRecordTime(DateTool.getTimestamp());
        }
        //调用JPA保存实体方法
        Certificate certificate1 = certificateDao.save(certificate);

        if (certificate1 != null) {
            return ResultFactory.buildSuccessResult(certificate1);
        } else {
            return ResultFactory.buildDefaultFailResult();
        }
    }

    /**
     * @describe 更新证书信息
     */
    @Override
    public Result updateCertificate(Certificate certificate) {
        if (certificate != null) {
            //获取系统当前时间作为记录更新时间
            certificate.setUpdateTime(DateTool.getTimestamp());
        }
        //调用JPA保存并刷新实体方法
        Certificate certificate1 = certificateDao.saveAndFlush(certificate);

        if (certificate1 != null) {
            return ResultFactory.buildSuccessResult(certificate1);
        } else {
            return ResultFactory.buildDefaultFailResult();
        }
    }

    /**
     * @describe 根据编号删除证书信息
     */
    @Override
    public Result deleteCertificateById(String certificateId) {

        int row = certificateDao.deleteByCertificateId(Integer.parseInt(certificateId));

        if (row > 0) {
            return ResultFactory.buildDefaultSuccessResult();
        } else {
            return ResultFactory.buildDefaultFailResult();
        }

    }

    /**
     * @describe 查询所有证书信息
     */
    @Override
    public Result queryAllCertificate() {

        List<Certificate> list = certificateDao.findAll();

        if (list != null) {
            return ResultFactory.buildSuccessResult(list);
        } else {
            return ResultFactory.buildDefaultFailResult();
        }
    }

    /**
     * @describe 根据编号查询该证书信息
     */
    @Override
    public Result queryCertificateById(String certificateId) {

        List<Certificate> list = certificateDao.findByCertificateId(Integer.parseInt(certificateId));

        if (list != null) {
            return ResultFactory.buildSuccessResult(list);
        } else {
            return ResultFactory.buildDefaultFailResult();
        }
    }
}
